<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Generic controller for entity class, CI AR.
 * @author hmQuan
 *
 */
class Users extends MY_Controller {

	//contructor class : call contructor of parent
	function __construct() {
		parent::__construct();
		$this->load->model('t_user');
		$this->load->model('gcmmodel');
	}

	public function index(){
		$this->load->view('welcome_message');
		// $this->login();
	}

	/**
	 * user login
	 * @return integer : 1|0
	 */
	public function login(){
		//get data post
		$post_data = $this->input->post();
		//check value post if !=null continue else return false
		$post_data = parent::check_post_value($post_data);
		$data =array();
		$log = array();
		//check database
		// token gcm
		$gcm_regid = $post_data[GCM_REGID];

		// user_id
		if(isset($post_data[USER_NAME]) && !empty($post_data[USER_NAME])){
			$data[USER_NAME] = $post_data[USER_NAME];
		}else{
			$log[USER_NAME] = INVALID;
		}

		// password 
		if(isset($post_data[USER_PASSWORD]) && !empty($post_data[USER_PASSWORD])){
			$data[USER_PASSWORD] = md5($post_data[USER_PASSWORD]);
		}else{
			$log[USER_PASSWORD] = INVALID;
		}

		if($log != null){
			parent::print_result( $log,FAILVALUE);
			exit();
		}

		// get infor from database
		$query = $this->t_user->get_data_by_property($data);
		// var_dump($query);exit();
		// login success
		if(!empty($query)){
			$this->t_user->update_data_by_id(array(USER_RESET_PASSWORD => 0), $query[0][USER_ID]);
			// unset : password, resetpassword, secretquestion
			unset($query[0][USER_PASSWORD]);
			unset($query[0][USER_RESET_PASSWORD]);	
			unset($query[0][USER_SECRET_QUESTION]);
			unset($query[0][USER_SECRET_ANSWER]);
			//update login table
			// update table login
			$update = array(GCM_ACTIVE => ISACTIVITY, USER_ID => $query[0][USER_ID]);
			$where = array(GCM_REGID => $gcm_regid);
			$this->gcmmodel->update_infor_gcm_by_property($update, $where);
			$gcm = $this->gcmmodel->get_data_by_property(array(LOGIN_USER_ID => $query[0][USER_ID], GCM_REGID => $gcm_regid));
			$query = array_merge($query[0], $gcm[0]);
			//return to client
			parent::print_result($query, SUCCESS_VALUE);
		}else{
			//failed
			$log[USER_NAME] = INVALID;
			$log[USER_PASSWORD] = INVALID;
			parent::print_result($log, FAILVALUE);
		}
		exit();
	}

	/**
	 * register user
	 */
	public function register($getInfo = 0){

		$post_data = $this->input->post();

		$post_data = parent::check_post_value($post_data);
		
		$data = array();
		$log = array();
		// check fields register
		// token
		$gcm_regid = $post_data[GCM_REGID];

		// username
		if(!empty($post_data[USER_NAME]) && isset($post_data[USER_NAME])){
			if(strlen($post_data[USER_NAME]) < MIN_LENGHT_USERNAME || strlen($post_data[USER_NAME]) > MAX_LENGHT_USERNAME){
				$log[USER_NAME] = INVALID;
			}else{
				// check unique username
				$queryUniqueName = $this->t_user->get_data_by_property(array(USER_NAME => $post_data[USER_NAME]));
				if(count($queryUniqueName) > 0){
					$log[USER_NAME] = EXISTED;
				}else{
					$data[USER_NAME] = $post_data[USER_NAME];	
				}
			}
		}else{
			$log[USER_NAME] = INVALID;
		}

		// password
		if(!empty($post_data[USER_PASSWORD]) && isset($post_data[USER_PASSWORD])){
			if(strlen($post_data[USER_PASSWORD]) < MIN_LENGHT_USERNAME ||strlen($post_data[USER_PASSWORD]) > MAX_LENGHT_USERNAME){
				$log[USER_PASSWORD] = INVALID;
			}else{
				$data[USER_PASSWORD] = md5($post_data[USER_PASSWORD]);
			}
		}else{
			$log[USER_PASSWORD] = INVALID;
		}
		// email
		if(!empty($post_data[USER_EMAIL]) &&isset($post_data[USER_EMAIL])){
			if(!$this->validate_email($post_data[USER_EMAIL])){
				$log[USER_EMAIL] = INVALID;
			}else{
				// check unique email
				$queryUniqueEmail = $this->t_user->get_data_by_property(array(USER_EMAIL => $post_data[USER_EMAIL]));
				if(count($queryUniqueEmail) > 0){
					$log[USER_EMAIL] = EXISTED;
				}else{
					$data[USER_EMAIL] = $post_data[USER_EMAIL];	
				}
			}
		}else{
			$log[USER_EMAIL] =  INVALID;
		}

		// phone number
		if(!empty($post_data[USER_PHONE_NUMBER]) && isset($post_data[USER_PHONE_NUMBER])){
			// check unique phone number
			$queryUniquePhone = $this->t_user->get_data_by_property(array(USER_PHONE_NUMBER => $post_data[USER_PHONE_NUMBER]));
			if(count($queryUniquePhone) > 0){
				$log[USER_PHONE_NUMBER] = EXISTED;
			}else{
				// check unique phone
				$queryUniquePhone = $this->t_user->get_data_by_property(array(USER_PHONE_NUMBER => $post_data[USER_PHONE_NUMBER]));
				if(count($queryUniqueEmail) > 0){
					$log[USER_PHONE_NUMBER] = EXISTED;
				}else{
					$data[USER_PHONE_NUMBER] = $post_data[USER_PHONE_NUMBER];	
				}	
			}
		}else{
			$log[USER_PHONE_NUMBER] = INVALID;
		}

		// secret question
		if(isset($post_data[USER_SECRET_QUESTION])){
			$data[USER_SECRET_QUESTION] = $post_data[USER_SECRET_QUESTION];
		}else{
			$log[USER_SECRET_QUESTION] = INVALID;
		}

		// secret answer
		if(isset($post_data[USER_SECRET_ANSWER])){
			$data[USER_SECRET_ANSWER] = $post_data[USER_SECRET_ANSWER];
		}else{
			$log[USER_SECRET_ANSWER] = INVALID;
		}

		// address and user permission
		$this->load->model('t_userpermission');
		$arrPermission = array();
		$arrPermission[UP_SELLER] = $this->t_userpermission->get_data_by_property(array(UP_TYPE => UP_SELLER));
		$arrPermission[UP_USER] = $this->t_userpermission->get_data_by_property(array(UP_TYPE => UP_USER));
		if(!empty($post_data[USER_ADDRESS]) && isset($post_data[USER_ADDRESS])){
			$data[USER_ADDRESS] = $post_data[USER_ADDRESS];
			$data[USER_PERMISSION_ID] = $arrPermission[UP_SELLER][0][UP_ID];
		}else{
			$data[USER_PERMISSION_ID] = $arrPermission[UP_USER][0][UP_ID];
		}

		if($log != null && count($log) > 0){
			parent::print_result($log);
			exit();
		}		
		
		// rate
		$data[USER_RATE] = RATE_DEFAULT;
		// reset password
		$data[USER_RESET_PASSWORD] = RESET_PASSWORD_DEFAULT;

		// insert database
		$user = $this->t_user->set_data($data, 1);

		$user_id = $user[0][USER_ID];

		// update path avatar
		$this->t_user->update_data_by_id(array(USER_AVATAR_PATH => UPLOAD_FOLDER_AVATARS . $user_id . '.' . UPLOAD_EXT_DEFAULT), $user_id);

		// update table login
		$update = array(GCM_ACTIVE => ISACTIVITY, USER_ID => $user_id);
		$where = array(GCM_REGID => $gcm_regid);
		$this->gcmmodel->update_infor_gcm_by_property($update, $where);
		$gcm = $this->gcmmodel->get_data_by_property(array(USER_ID => $user_id, GCM_REGID => $gcm_regid));
		$user = array_merge($user[0], $gcm[0]);
		//return result
		// unset : password, resetpassword, secretquestion
		unset($user[0][USER_PASSWORD]);
		unset($user[0][USER_RESET_PASSWORD]);
		unset($user[0][USER_SECRET_QUESTION]);
		unset($user[0][USER_SECRET_ANSWER]);
		//return to client
		parent::print_result($user, SUCCESS_VALUE);

		// send email
		// $email_user = $user[0][USER_EMAIL];

		// $this->load->model('T_email_template');

		// require_once("parse.php");
		
		// $get_parse_email = new ParserEmailTemplate();

		// $get_parse_email->get_template_welcome(array('template' => 'WELCOME_USER'));

		// $parse_email = $get_parse_email->public_template['template'];

		// $parse_subject = $get_parse_email->public_template['subject'];

		// if (!empty($parse_email) && !empty($parse_subject) )
		// {
		// 	require_once("email.php");
		// 	$sendemail = new Email();

		// 	$arraymail = array('SUBJECT' => $parse_subject, 'TO' => $email_user , 'BODY' => $parse_email );

		// 	// send mail
		// 	if($sendemail->send_mail($arraymail)){
		// 	}
		// }
		// email
		// $email_config = Array(
  //           'protocol'  => 'smtp',
  //           'smtp_host' => 'ssl://smtp.googlemail.com',
  //           'smtp_port' => '465',
  //           'smtp_user' => 'vietdreamtech@gmail.com',
  //           'smtp_pass' => '@h4ck3r#',
  //           'mailtype'  => 'html',
  //           'starttls'  => true,
  //           'newline'   => "\r\n"
  //       );

  //       $this->load->library('email', $email_config);

  //       $this->email->from('vietdreamtech@gmail.com', 'invoice');
  //       $this->email->to('hoangminhquan90@gmail.com');
  //       $this->email->subject('Invoice');
  //       $this->email->message('Test');

  //       $this->email->send();
		exit();
	}

	/**
	 * get user information
	 * @return [type] [description]
	 */
	public function get_user_infor(){
		$post = $this->input->post();
		$post = parent::check_post_value($post);

		if(!isset($post[USER_ID])){
			parent::print_result('Missing key or value ' . USER_ID);exit();
		}else{
			$user_id = $post[USER_ID];
		}

		if(isset($post[USER_UPDATE]) && !empty($post[USER_UPDATE])){
			$fields = $post[USER_UPDATE];
		}else{
			$fields = '*';
		}

		$query = $this->t_user->get_data_by_id($user_id, $fields);
		if(empty($query)){
			parent::print_result('User does not exist');
		}else{
			unset($query[0][USER_PASSWORD]);
			unset($query[0][USER_RESET_PASSWORD]);
			unset($query[0][USER_SECRET_QUESTION]);
			unset($query[0][USER_SECRET_ANSWER]);
			
			parent::print_result($query[0], SUCCESS_VALUE);	
		}
		exit();
	}

	// update infor user
	public function update_infor_user(){
		$post = parent::validation_user();
		// regid
		$gcm_regid = $post[GCM_REGID];

		$user_id = $post[T_USERS][USER_ID];
		
		if (isset($post[USER_TYPE])) {
			$type = $post[USER_TYPE];	
		}else{
			parent::print_result('Missing key or value '. USER_TYPE);exit();
		}

		if (isset($post[USER_VALUE])) {
			$value = $post[USER_VALUE];
		}else{
			parent::print_result('Missing key or value '. USER_VALUE);exit();	
		}

		if(isset($post[USER_SECRET_QUESTION])){
			$secretQuestion = $post[USER_SECRET_QUESTION];
		}else{
			parent::print_result('Missing key or value ' . USER_SECRET_QUESTION);exit();
		}

		if(isset($post[USER_SECRET_ANSWER])){
			$secretAnswer = $post[USER_SECRET_ANSWER];
		}else{
			parent::print_result('Missing key or value ' . USER_SECRET_ANSWER);exit();
		}

		if($type == 0){
			$update = $this->t_user->update_data_by_id(array(USER_ADDRESS => $value), $user_id);
		}else if($type == 1){

			$e = $this->t_user->get_data_by_property(array(USER_EMAIL => $value));

			if(empty($e)){
				$update = $this->t_user->update_data_by_property(array(USER_EMAIL => $value), array(USER_ID => $user_id, USER_SECRET_QUESTION => $secretQuestion, USER_SECRET_ANSWER => $secretAnswer));	
			}else{
				parent::print_result('email existed');exit();
			}

			
		}else if($type == 2){
			$p = $this->t_user->get_data_by_property(array(USER_PHONE_NUMBER => $value));
			if(empty($p)){
				$update = $this->t_user->update_data_by_property(array(USER_PHONE_NUMBER => $value), array(USER_ID => $user_id, USER_SECRET_QUESTION => $secretQuestion, USER_SECRET_ANSWER => $secretAnswer));
			}else{
				parent::print_result('phone number existed');exit();	
			}

		}

		if(!empty($update) && $update > 0){
			$query = $this->t_user->get_data_by_id($user_id);
			$gcm = $this->gcmmodel->get_data_by_property(array(LOGIN_USER_ID => $query[0][USER_ID], GCM_REGID => $gcm_regid));
			$query = array_merge($query[0], $gcm[0]);

			$this->load->model(T_GCMMODEL);
			$arrGcm = $this->gcmmodel->get_data_by_property(array(LOGIN_USER_ID => $user_id, LOGIN_IS_ACTIVITY => 1));
			parent::push_notification_to_client_via_user_id($user_id, PUSH_MSG_CHANGE_USER_INFOR, PUSH_CHANGE_USER_INFOR, $user_id);

			parent::print_result($query, SUCCESS_VALUE);exit();
		}else{
			parent::print_result('Update failed');exit();
		}
	}

	/**
	 * change password user
	 * @return integer
	 */
	public function change_password(){

		$post_data = parent::validation_user();

		// check user
		// gcm id
		$gcm_regid = $post_data[GCM_REGID];
		// user id
		$user_id = $post_data[T_USERS][USER_ID];
		// var_dump($user_id);exit();
		$log = array();
		$data = array();
		// confirm post value
		
		if(empty($post_data[USER_PASSWORD]) || !isset($post_data[USER_PASSWORD]) || strlen($post_data[USER_PASSWORD]) <6 || strlen($post_data[USER_PASSWORD]) > MAX_LENGHT_USERNAME){
			$log[USER_PASSWORD] = INVALID;
		}
		if(empty($post_data[USER_NEW_PASSWORD]) || !isset($post_data[USER_NEW_PASSWORD]) || strlen($post_data[USER_NEW_PASSWORD]) <6 || strlen($post_data[USER_NEW_PASSWORD]) > MAX_LENGHT_USERNAME){
			$log[USER_NEW_PASSWORD] = INVALID;
		}

		// if error return
		if($log != null){
			parent::print_result($log, FAILVALUE);
			exit();
		}

		//query
		$result = $this->t_user->update_data_by_property(array(USER_PASSWORD => md5($post_data[USER_NEW_PASSWORD])), array(USER_PASSWORD => md5($post_data[USER_PASSWORD]), USER_ID => $user_id));

		if(count($result) != 0){
			// return success
			parent::print_result('Change password success', SUCCESS_VALUE);

			// update session activity gcm and push notification
			// push notification to clients
			$this->load->model(T_GCMMODEL);
			$arrGcm = $this->gcmmodel->get_data_by_property(array(LOGIN_USER_ID => $user_id, LOGIN_IS_ACTIVITY => 1));
			parent::push_notification_to_client_via_user_id($user_id, PUSH_MSG_CHANGE_USER_INFOR, PUSH_CHANGE_USER_INFOR, $user_id);
			// // update session
			if(!empty($arrGcm)){
				foreach ($arrGcm as $key => $user_gcm) {
					if(strcmp($user_gcm[GCM_REGID], $gcm_regid) != 0){
						$update = array(GCM_ACTIVE => 0);
						$where = array(GCM_REGID => $user_gcm[GCM_REGID], USER_ID => $user_gcm[USER_ID]);
						$this->gcmmodel->update_infor_gcm_by_property($update, $where);
					}
				}	
			}
			

			// send email notification
			// send email contain new password
			// $this->load->model('T_email_template');

			// require_once("parse.php");
			
			// $get_parse_email = new ParserEmailTemplate();
			
			// $get_parse_email->get_template_change_password();

			// $parse_email = $get_parse_email->public_template['template'];

			// $parse_subject = $get_parse_email->public_template['subject'];

			// if (!empty($parse_email) && !empty($parse_subject) )
			// {
			// 	require_once("email.php");

			// 	$sendemail = new Email();

			// 	$arraymail = array('SUBJECT' => $parse_subject, 'TO' => $email_user , 'BODY' => $parse_email );

			// 	// send mail
			// 	if($sendemail->send_mail($arraymail)){
			// 	}
			// }
		}else{
			parent::print_result('Change password failed');
		}
		exit();
	}

	/**
	 * restore password for user
	 * @return new password via email register
	 */
	public function reset_password(){
		$post = $this->input->post();
		$post = parent::check_post_value($post);

		$gcm_regid = $post[GCM_REGID];
		$data = array();
		// validation post
		if(!isset($post[USER_EMAIL]) || empty($post[USER_EMAIL])){
			parent::print_result('Missing key or value ' . USER_EMAIL);exit();
		}else{
			$data[USER_EMAIL] = $post[USER_EMAIL];
			
		}

		if(!isset($post[USER_SECRET_QUESTION])){
			parent::print_result('Missing key or value null ' . USER_SECRET_QUESTION);exit();
		}else{
			$data[USER_SECRET_QUESTION] = $post[USER_SECRET_QUESTION];
		}

		if(!isset($post[USER_SECRET_ANSWER])){
			parent::print_result('Missing key or value null ' . USER_SECRET_ANSWER);exit();
		}else{
			$data[USER_SECRET_ANSWER] = $post[USER_SECRET_ANSWER];
		}

		// retrieve user by post data
		$user = $this->t_user->get_data_by_property($data);

		if(empty($user)){
			parent::print_result('User does not exist which match your information');exit();
		}else{
			$user_id = $user[0][USER_ID];
		}

		// general password
		$random_password = $this->random_password();
		// update new password
		$this->t_user->update_data_by_id(array(USER_RESET_PASSWORD => $random_password), $user_id);
		//return success
		parent::print_result('Reset password success', SUCCESS_VALUE);

		// send email contain new password
		$this->load->model('T_email_template');

		require_once("parse.php");
		
		$get_parse_email = new ParserEmailTemplate();

		$data_sendmail = array('NEWPASSWORD' => $random_password);
		
		$get_parse_email->get_template_reset_password($data_sendmail);

		$parse_email = $get_parse_email->public_template['template'];

		$parse_subject = $get_parse_email->public_template['subject'];

		if (!empty($parse_email) && !empty($parse_subject) )
		{
			require_once("email.php");

			$sendemail = new Email();

			$arraymail = array('SUBJECT' => $parse_subject, 'TO' => $email_user , 'BODY' => $parse_email );

			require_once('gcmusers.php');
			$gcmusers = new GCMUsers();

			// action send mail
			$sendemail->send_mail($arraymail);
			
		}

		// push notification to clients
		// $arrGcm = $this->t_user->get_all_gcm($user_id);
		$gcmInfor = $this->gcmmodel->get_data_by_property(array(LOGIN_USER_ID => $user_id, LOGIN_IS_ACTIVITY => 1));
		$arrGcmRegId = array();
		foreach ($gcmInfor as $key => $user_gcm) {
			$arrGcmRegId[] = $user_gcm[GCM_REGID];
		}
		// push				
		$gcmusers->send_notification_android($arrGcmRegId, CHANGE_PASSWORD_SUCCESS);
		exit();
	}

	/**
	 * search user via username
	 * @return [type] [description]
	 */
	public function get_user_infor_by_username(){

		$post = $this->input->post();
		$post = parent::check_post_value($post);

		if(!isset($post[USER_NAME]) || empty($post[USER_NAME])){
			parent::print_result('missing key or value ' . USER_NAME);exit();
		}
		$arrUserInfor = $this->t_user->get_data_by_property(array(USER_NAME .' LIKE ' => '%'.$post[USER_NAME].'%'));
		
		if($arrUserInfor == null || count($arrUserInfor) == 0){
			parent::print_result('No users found which match your users name');exit();
		}else{
			// unset : password, resetpassword, secretquestion
			foreach ($arrUserInfor as $key => $user) {
				unset($arrUserInfor[$key][USER_PASSWORD]);
				unset($arrUserInfor[$key][USER_RESET_PASSWORD]);
				unset($arrUserInfor[$key][USER_SECRET_QUESTION]);
				unset($arrUserInfor[$key][USER_SECRET_ANSWER]);	
			}
			parent::print_result($arrUserInfor, SUCCESS_VALUE);exit();
		}
	}

	/**
	 * [get_products_purchased : get list product which user purchased]
	 * @return [type] [description]
	 */
	public function get_products_purchased(){
		$post = parent::validation_user();
		$arrProductPurchased = $this->t_user->get_products_purchased($post[T_USERS][USER_ID]);
		if(empty($arrProductPurchased)){
			parent::print_result('You does not purchased');exit();
		}else{
			parent::print_result($arrProductPurchased, SUCCESS_VALUE);exit();	
		}
		
	}

	

	/**
	 * [get_history_product description]
	 * @return [type] [description]
	 */
	public function get_history_product(){
		$post = parent::validation_user();
		$userId = $post[T_USERS][USER_ID];
		$history = $this->t_user->get_history_product($userId);
		if(empty($history)){
			parent::print_result(0, SUCCESS_VALUE);
		}else{
			parent::print_result($history, SUCCESS_VALUE);
		}
		exit();
	}

	public function get_all_user(){
		$post = $this->input->post();
		$post = parent::check_post_value($post);

		if(isset($post['page'])){
			$page = $post['page'];
		}else{
			$page = 0;
		}
		if(isset($post['per_page'])){
			$per_page = $post['per_page'];
		}else{
			$per_page = 100;
		}

		$users = $this->t_user->get_all_user($page, $per_page);
		if(empty($users)){
			parent::print_result(0,SUCCESS_VALUE);
		}else{
			parent::print_result($users, SUCCESS_VALUE);
		}
		exit();
	}

	/**
	 * [random_password description]
	 * @return string [description]
	 * format same : Abc1a5g - Lenght = 8
	 */
	private function random_password($length = 8)
	{
	   	mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.

	   	$charid=strtoupper(md5(uniqid(rand(), true)));

	   	$uuid=substr($charid, 0, $length);

	   	return $uuid;
	}

	private function validate_email($email = '') {
		return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[	 ])+|(?>[	 ]*\x0D\x0A)?[	 ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){7,})((?6)(?>:(?6)){0,5})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){5,})(?8)?::(?>((?6)(?>:(?6)){0,3}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $email);
  	}
}